#include "TrueText/Config.h"
#include "PixelFormatHelpers.h"
#include "TrueText/Error.h"

namespace TrueText {

size_t GetBytesPerPixel(PixelFormat fmt)
{
	switch (fmt)
	{
	case PIXEL_FORMAT_ARGB_8888:
	case PIXEL_FORMAT_BGRA_8888:
		return 4;
	default:
		TRUE_TEXT_THROW(Error(L"Cannot get bytes per pixel for unsupported pixel format"));
	}
}

Color GetPixelColor(const void* src, PixelFormat fmt)
{
	const int* srcInt = reinterpret_cast<const int*>(src);

	switch (fmt)
	{
	case PIXEL_FORMAT_ARGB_8888:
		{
			Color result;
			result.a = (*srcInt >> 24) & 0xFF;
			result.r = (*srcInt >> 16) & 0xFF;
			result.g = (*srcInt >> 8) & 0xFF;
			result.b = *srcInt & 0xFF;
			return result;
		}
	case PIXEL_FORMAT_BGRA_8888:
		{
			Color result;
			result.b = (*srcInt >> 24) & 0xFF;
			result.g = (*srcInt >> 16) & 0xFF;
			result.r = (*srcInt >> 8) & 0xFF;
			result.a = *srcInt & 0xFF;
			return result;
		}
	}

	TRUE_TEXT_THROW(Error(L"Cannot parse pixel of unknown pixel format"));
}

void SetPixelColor(void* dst, PixelFormat fmt, Color color)
{
	int* dstInt = reinterpret_cast<int*>(dst);

	switch(fmt)
	{
	case PIXEL_FORMAT_ARGB_8888:
		*dstInt = (color.a << 24) | (color.r << 16) | (color.g << 8) | color.b;
		return;
	case PIXEL_FORMAT_BGRA_8888:
		*dstInt = (color.b << 24) | (color.g << 16) | (color.r << 8) | color.a;
		return;
	}

	TRUE_TEXT_THROW(Error(L"Cannot write pixel of unknown pixel format"));
}

}